package qeug.shsh.opplugin;

import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.form.*;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.fi.bcm.fel.common.NumberUtil;
import org.jetbrains.annotations.NotNull;
import java.math.BigDecimal;
import java.util.*;

public class FeeRequestListPlugin extends AbstractListPlugin {

    /**
     * 事前申请单列表插件
     */
    private static String SUBMIT = "tblsubmit";//提交按钮
    private static String UNSUBMIT = "tblunsubmit";//撤销按钮
    private static String INVALID = "invalid";//废弃按钮
    private static String RECORD = "qeug_approval_record";//查看审批记录


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("tbmain");//监听按钮
    }

    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
        Set<Long> setIds = getSelectOrderIds(this.getSelectedRows());
        if (evt.getItemKey().equals(SUBMIT)) {
            // 提交按钮
            if (setIds.size() == 0) {
                return;
            }
            boolean allValid = true; // 标志位，初始值为true
            List<DynamicObject> orderList = new ArrayList<>(); // 定义一个列表用于存储多条数据
            int count = 0;
            for (Long id : setIds) {
                count++;
                DynamicObject receiveApplication = BusinessDataServiceHelper.loadSingle("er_dailyapplybill", "billstatus,qeug_document_type,qeug_application,qeug_supplies,qeug_inventory_quantity", new QFilter[]{new QFilter("id", QCP.equals, id)});
                int haveSuppliers = 0; // 有供应商的行数
                int correctQuantity = 0; // 提交正确的行数
                DynamicObjectCollection expenseCollection = receiveApplication.getDynamicObjectCollection("expenseentryentity");
                DynamicObject billTypeNumber = receiveApplication.getDynamicObject("qeug_document_type");// 单据类型
                String billType = billTypeNumber.getString("number");
                String billStatusNumber = receiveApplication.getString("billstatus");// 单据状态
                if ("er_dailyapplybill_BT2".equals(billType) && "A".equals(billStatusNumber)) {
                    for (DynamicObject expense : expenseCollection) {
                        BigDecimal application = expense.getBigDecimal("qeug_application");// 申请数量
                        DynamicObject supplies = expense.getDynamicObject("qeug_supplies");// 物料
                        if (supplies != null) {
                            haveSuppliers++;
                            QFilter[] qFilter = new QFilter[]{
                                    new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                            DynamicObject inventory = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_inventory_quantit,qeug_total_quantity,qeug_quantity_used,qeug_supplies", qFilter);
                            BigDecimal inventory_quantity = inventory.getBigDecimal("qeug_inventory_quantit");// 库存数量
                            BigDecimal total_quantity = inventory.getBigDecimal("qeug_total_quantity");// 总数量
                            BigDecimal quantity = inventory_quantity.subtract(application);// 剩余库存数量
                            BigDecimal subtract = total_quantity.subtract(quantity);// 已用数量
                            if (inventory_quantity.compareTo(application) >= 0) {
                                String suppliesNumber = supplies.getString("number");
                                if (count != 1) {
                                    for (int i = 0; i < orderList.size(); i++) {
                                        DynamicObject dynamicObject = orderList.get(i);
                                        DynamicObject supplies1 = dynamicObject.getDynamicObject("qeug_supplies");
                                        String supplieNumber = supplies1.getString("number");
                                        if (suppliesNumber.equals(supplieNumber)) {
                                            orderList.remove(i);
                                            BigDecimal inventory_quantitys = dynamicObject.getBigDecimal("qeug_inventory_quantit");// 库存数量
                                            BigDecimal total_quantitys = dynamicObject.getBigDecimal("qeug_total_quantity");// 总数量
                                            BigDecimal quantitys = inventory_quantitys.subtract(application);// 剩余库存数量
                                            BigDecimal subtracts = total_quantitys.subtract(quantitys);// 已用数量
                                            if (inventory_quantitys.compareTo(application) >= 0) {
                                                inventory.set("qeug_inventory_quantit", quantitys);
                                                inventory.set("qeug_quantity_used", subtracts);
                                                orderList.add(inventory); // 将 inventory 对象添加到列表中
                                                correctQuantity++;
                                                break;
                                            } else {
                                                allValid = false; // 如果有一条信息不满足条件，将标志位置为false
                                                break;
                                            }
                                        } else {
                                            inventory.set("qeug_inventory_quantit", quantity);
                                            inventory.set("qeug_quantity_used", subtract);
                                            orderList.add(inventory); // 将 inventory 对象添加到列表中
                                            correctQuantity++;
                                            break;
                                        }
                                    }
                                } else {
                                    inventory.set("qeug_inventory_quantit", quantity);
                                    inventory.set("qeug_quantity_used", subtract);
                                    orderList.add(inventory); // 将 inventory 对象添加到列表中
                                    correctQuantity++;
                                }
                            }
                        }
                    }
                }
                if (haveSuppliers != correctQuantity) {
                    allValid = false; // 如果有一条信息不满足条件，将标志位置为false
                }
            }
            if (allValid) {
                for (Long id : setIds) {
                    DynamicObject receiveApplication = BusinessDataServiceHelper.loadSingle("er_dailyapplybill", "billstatus,qeug_document_type,qeug_application,qeug_supplies,qeug_inventory_quantity", new QFilter[]{new QFilter("id", QCP.equals, id)});
                    DynamicObjectCollection expenseCollection = receiveApplication.getDynamicObjectCollection("expenseentryentity");
                    DynamicObject billTypeNumber = receiveApplication.getDynamicObject("qeug_document_type");// 单据类型
                    String billType = billTypeNumber.getString("number");
                    String billStatusNumber = receiveApplication.getString("billstatus");// 单据状态
                    if ("er_dailyapplybill_BT2".equals(billType) && "A".equals(billStatusNumber)) {
                        for (DynamicObject expense : expenseCollection) {
                            BigDecimal application = expense.getBigDecimal("qeug_application");// 申请数量
                            DynamicObject supplies = expense.getDynamicObject("qeug_supplies");// 物料
                            if (supplies != null) {
                                QFilter[] qFilter = new QFilter[]{
                                        new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                                DynamicObject inventory = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_inventory_quantit,qeug_total_quantity,qeug_quantity_used", qFilter);
                                BigDecimal inventory_quantity = inventory.getBigDecimal("qeug_inventory_quantit");// 库存数量
                                BigDecimal total_quantity = inventory.getBigDecimal("qeug_total_quantity");// 总数量
                                BigDecimal quantity = inventory_quantity.subtract(application);// 剩余库存数量
                                BigDecimal subtract = total_quantity.subtract(quantity);// 已用数量
                                if (inventory_quantity.compareTo(application) >= 0) {
                                    inventory.set("qeug_inventory_quantit", quantity);
                                    inventory.set("qeug_quantity_used", subtract);
                                    DynamicObject[] order = new DynamicObject[]{inventory};
                                    SaveServiceHelper.save(order); // 保存全部数据
                                }
                            }
                        }
                    }
                }
                /*if (!orderList.isEmpty()) {
                    DynamicObject[] order = orderList.toArray(new DynamicObject[0]); // 将列表转换为数组
                }*/
            } else {
                evt.setCancel(true); // 取消原来的操作
                this.getView().showErrorNotification("选中的单据中存在申请数量超过剩余库存数量！请刷新费用明细");
            }
        } else if (evt.getItemKey().equals(UNSUBMIT)) {
            //撤销按钮
            if (setIds.size() == 0) {
                return;
            }
            DynamicObject[] receiveApplications = BusinessDataServiceHelper.load("er_dailyapplybill", "billstatus,qeug_document_type,qeug_application,qeug_supplies,qeug_inventory_quantity", new QFilter[]{new QFilter("id", "in", setIds)});
            for (DynamicObject receiveApplication : receiveApplications) {
                DynamicObjectCollection expenseCollection = receiveApplication.getDynamicObjectCollection("expenseentryentity");
                DynamicObject billTypeNumber = receiveApplication.getDynamicObject("qeug_document_type");//单据类型
                String billType = billTypeNumber.getString("number");
                String billStatusNumber = receiveApplication.getString("billstatus");//单据状态
                if ("er_dailyapplybill_BT2".equals(billType) && "B".equals(billStatusNumber)) {
                    for (DynamicObject expense : expenseCollection) {
                        BigDecimal application = expense.getBigDecimal("qeug_application");//申请数量
                        DynamicObject supplies = expense.getDynamicObject("qeug_supplies");//物料
                        if (supplies != null) {
                            QFilter[] qFilter = new QFilter[]{
                                    new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                            DynamicObject inventory = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_inventory_quantit,qeug_total_quantity,qeug_quantity_used", qFilter);
                            BigDecimal inventory_quantity = inventory.getBigDecimal("qeug_inventory_quantit");//库存数量
                            BigDecimal total_quantity = inventory.getBigDecimal("qeug_total_quantity");//总数量
                            BigDecimal quantity = inventory_quantity.add(application);//剩余库存数量
                            BigDecimal subtract = total_quantity.subtract(quantity);//已用数量
                            inventory.set("qeug_inventory_quantit", quantity);
                            inventory.set("qeug_quantity_used", subtract);
                            DynamicObject[] order = new DynamicObject[]{inventory};
                            SaveServiceHelper.save(order);
                        }
                    }
                }
            }
        } else if (evt.getItemKey().equals(INVALID)) {
            //废弃按钮
            if (setIds.size() == 0) {
                return;
            }
            evt.setCancel(true);//取消原来的操作
            //作废操作前让用户选择是否继续作废操作，在用户点击确认框上的按钮后，系统会调用confirmCallBack方法
            ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener("feiqiction", this);
            //设置页面确认框，参数为：标题，选项框类型，回调监听
            this.getView().showConfirm("单据即将废弃，是否继续？？", MessageBoxOptions.YesNo, confirmCallBackListener);
        } else if (evt.getItemKey().equals(RECORD)) {
            if (setIds.size() == 0) {
                this.getView().showTipNotification("请选择要执行的数据。");
                return;
            }
            DynamicObject[] receiveApplications = BusinessDataServiceHelper.load("er_dailyapplybill", "billno,qeug_processinstance", new QFilter[]{new QFilter("id", "in", setIds)});
            for (DynamicObject receiveApplication : receiveApplications) {
                String bill = receiveApplication.getString("billno");//单据编号
//                String processInstance = receiveApplication.getString("qeug_processinstance");//BPM审批流
                QFilter[] qFilter = new QFilter[]{
                        new QFilter("billno", QCP.equals, bill)};
                DynamicObject inventory = BusinessDataServiceHelper.loadSingle("qeug_auditlog", "billno", qFilter);
                if (inventory != null) {
                    String pkId = inventory.getString("id");
                    BillShowParameter showParameter = new BillShowParameter();
                    showParameter.setFormId("qeug_auditlog");
                    showParameter.getOpenStyle().setShowType(ShowType.Modal); //打开方式
                    showParameter.setPkId(pkId);
                    if (showParameter.getFormConfig() == null) {
                        showParameter.setFormConfig(FormMetadataCache.getFormConfig("qeug_auditlog"));
                    }
                    showParameter.getFormConfig().setHeight(new LocaleString("650"));
                    showParameter.getFormConfig().setWidth(new LocaleString("1200"));
                    getView().showForm(showParameter);
                } else {
                    this.getView().showErrorNotification(bill + "无审批记录！");
                }
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);
        Set<Long> setIds = getSelectOrderIds(this.getSelectedRows());
        if ("feiqiction".equals(messageBoxClosedEvent.getCallBackId())) {
            if (MessageBoxResult.Yes.equals(messageBoxClosedEvent.getResult())) {
                //作废操作点击确认后执行之后的操作
                DynamicObject[] receiveApplications = BusinessDataServiceHelper.load("er_dailyapplybill", "billstatus,qeug_document_type,qeug_application,qeug_supplies,qeug_inventory_quantity", new QFilter[]{new QFilter("id", "in", setIds)});
                for (DynamicObject receiveApplication : receiveApplications) {
                    DynamicObjectCollection expenseCollection = receiveApplication.getDynamicObjectCollection("expenseentryentity");
                    DynamicObject billTypeNumber = receiveApplication.getDynamicObject("qeug_document_type");//单据类型
                    String billType = billTypeNumber.getString("number");
                    String billStatusNumber = receiveApplication.getString("billstatus");//单据状态
                    if ("er_dailyapplybill_BT2".equals(billType) && ("B".equals(billStatusNumber)) || "D".equals(billStatusNumber)) {
                        for (DynamicObject expense : expenseCollection) {
                            BigDecimal application = expense.getBigDecimal("qeug_application");//申请数量
                            DynamicObject supplies = expense.getDynamicObject("qeug_supplies");//物料
                            if (supplies != null) {
                                QFilter[] qFilter = new QFilter[]{
                                        new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                                DynamicObject inventory = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_inventory_quantit,qeug_total_quantity,qeug_quantity_used", qFilter);
                                BigDecimal inventory_quantity = inventory.getBigDecimal("qeug_inventory_quantit");//库存数量
                                BigDecimal total_quantity = inventory.getBigDecimal("qeug_total_quantity");//总数量
                                BigDecimal quantity = inventory_quantity.add(application);//剩余库存数量
                                BigDecimal subtract = total_quantity.subtract(quantity);//已用数量
                                if (inventory_quantity.compareTo(application) >= 0) {
                                    inventory.set("qeug_inventory_quantit", quantity);
                                    inventory.set("qeug_quantity_used", subtract);
                                    DynamicObject[] order = new DynamicObject[]{inventory};
                                    SaveServiceHelper.save(order);
                                }
                            }
                        }
                    }
                }
                this.getView().invokeOperation(INVALID); //继续调用废弃操作
            }
        }
    }

    @NotNull
    private Set<Long> getSelectOrderIds(@NotNull ListSelectedRowCollection selectedRows) {
        Set<Long> setIds = new HashSet<>();
        for (ListSelectedRow selectedRow : selectedRows) {
            setIds.add(NumberUtil.toLong(selectedRow.getPrimaryKeyValue()));
        }
        return setIds;
    }
}

